<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="dataForm.name" placeholder="商品名称"></el-input>
      </el-form-item>
      <el-form-item label="主图" prop="defaultImgPreview">
        <!-- <el-input v-model="dataForm.defaultImg" placeholder="主图"></el-input> -->
        <el-upload
          :action="uploadUrl"
          list-type="picture-card"
          :on-remove="handleRemove"
          :on-success="handleUploadSuccess"
          :limit="1"
          :file-list="defaultImgList"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>

      <!-- <el-form-item label="主图" prop="defaultImg">
        <el-input v-model="dataForm.defaultImg" placeholder="主图"></el-input>
      </el-form-item> -->

      <el-form-item label="图片" prop="imgUrls">
        <!-- <el-input v-model="dataForm.imgUrls" placeholder="图片"></el-input> -->

        <el-upload
          :on-success="handleImgUploadSuccess"
          :action="uploadUrl"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="removeImg"
          :file-list="imgList"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="dataForm.description" placeholder="描述"></el-input>
      </el-form-item>
      <el-form-item label="基础价格" prop="basePrice">
        <el-input
          v-model="dataForm.basePrice"
          placeholder="基础价格"
        ></el-input>
      </el-form-item>
      <!-- <el-form-item label="销量" prop="saleCount">
        <el-input v-model="dataForm.saleCount" placeholder="销量"></el-input>
      </el-form-item> -->
      <el-form-item label="商品分类" prop="categoryId">
        <!-- <el-input
          v-model="dataForm.categoryId"
          placeholder="商品分类名称"
        ></el-input> -->

        <el-select v-model="dataForm.categoryId" placeholder="请选择">
          <el-option
            v-for="item in categotyList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data () {
    return {
      // 图片预览
      imgList: [],
      // 主图回显
      defaultImgList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      categotyList: [],
      uploadUrl: '',
      visible: false,
      dataForm: {
        id: 0,
        name: '',
        defaultImg: '',
        imgUrls: '',
        description: '',
        basePrice: '',
        saleCount: 0,
        categoryId: '',
        version: '',
        createTime: '',
        updateTime: ''
      },
      dataRule: {
        name: [
          { required: true, message: '商品名称不能为空', trigger: 'blur' }
        ],
        // defaultImg: [
        //   { required: true, message: '主图不能为空', trigger: 'blur' }
        // ],
        // imgUrls: [{ required: true, message: '图片不能为空', trigger: 'blur' }],
        description: [
          { required: true, message: '描述不能为空', trigger: 'blur' }
        ],
        basePrice: [
          { required: true, message: '基础价格不能为空', trigger: 'blur' }
        ],
        // saleCount: [
        //   { required: true, message: '销量不能为空', trigger: 'blur' }
        // ],
        categoryId: [
          { required: true, message: '商品分类id不能为空', trigger: 'blur' }
        ],
        version: [
          { required: true, message: '版本号不能为空', trigger: 'blur' }
        ],
        createTime: [
          { required: true, message: '创建时间不能为空', trigger: 'blur' }
        ],
        updateTime: [
          { required: true, message: '修改时间不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    handleImgUploadSuccess (response, file, fileList) {
      this.imgList.push(file)
      console.log('fileList', fileList)
    },
    removeImg (file, fileList) {
      console.log('移除文件', file)
      const index = this.imgList.indexOf(file)
      if (index > -1) {
        this.imgList.splice(index, 1)
      }
    },
    // 图片预览
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 主图删除
    handleRemove (file, fileList) {
      this.dataForm.defaultImg = ''
    },
    // 主图上传成功
    handleUploadSuccess (response, file, fileList) {
      if (response && response.code === 0) {
        this.dataForm.defaultImg = response.url
      } else {
        this.$message.error('图片上传失败')
      }
    },
    queryCategotyList () {
      this.$http({
        url: this.$http.adornUrl('/productcategory/all'),
        method: 'get'
      }).then(({ data }) => {
        // console.log(data)
        this.categotyList = data && data.code === 0 ? data.data : []
      })
    },
    init (id) {
      // 删除主图、图片
      this.imgList = []
      this.defaultImgList = []
      this.queryCategotyList()
      // 上传地址
      this.uploadUrl = this.$http.adornUrl(
        `/sys/oss/upload?token=${this.$cookie.get('token')}`
      )

      this.dataForm.id = id || 0
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(`/product/info/${this.dataForm.id}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.name = data.product.name
              this.dataForm.defaultImg = data.product.defaultImg
              // 回显主图

              this.defaultImgList = [
                { name: 'food.jpg', url: data.product.defaultImg }
              ]
              this.dataForm.imgUrls = data.product.imgUrls
              // 回显图片
              let tempImgList = []
              if (!data.product.imgUrls) {
                this.imgList = tempImgList
              } else {
                if (data.product.imgUrls.indexOf(';') < 0) {
                  this.imgList = [
                    { name: 'food.jpg', url: data.product.imgUrls }
                  ]
                } else {
                  // 图片数组
                  for (const img of data.product.imgUrls.split(';')) {
                    if (img) {
                      tempImgList.push({ name: 'food.jpg', url: img })
                    }
                  }
                  this.imgList = tempImgList
                }
              }

              this.dataForm.description = data.product.description
              this.dataForm.basePrice = data.product.basePrice
              this.dataForm.saleCount = data.product.saleCount
              this.dataForm.categoryId = data.product.categoryId
              this.dataForm.version = data.product.version
              this.dataForm.createTime = data.product.createTime
              this.dataForm.updateTime = data.product.updateTime
            }
          })
        }
      })
    },
    // 表单提交
    dataFormSubmit () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // 图片用；拼接
          let urls = ''
          for (const item of this.imgList) {
            // 如果是之前回显的图片
            if (item.url && !item.url.indexOf('blob') == -1) {
              urls += item.url + ';'
            } else if (item.response.url) {
              urls += item.response.url + ';'
            }
          }
          console.log('urls', urls)

          this.$http({
            url: this.$http.adornUrl(
              `/product/${!this.dataForm.id ? 'save' : 'update'}`
            ),
            method: 'post',
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              name: this.dataForm.name,
              defaultImg: this.dataForm.defaultImg,

              imgUrls: urls,
              description: this.dataForm.description,
              basePrice: this.dataForm.basePrice,
              saleCount: this.dataForm.saleCount,
              categoryId: this.dataForm.categoryId,
              version: this.dataForm.version,
              createTime: this.dataForm.createTime,
              updateTime: this.dataForm.updateTime
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false

                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    }
  }
}
</script>
